package com.xx.cloud.pay.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xx.cloud.pay.entity.DynamicCode;
import com.xx.cloud.pay.mapper.DynamicCodeMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class QrCodeController {

    @Autowired
    private DynamicCodeMapper dynamicCodeMapper;
    
//    public QrCodeController(DynamicCodeRepository repository) {
//        this.repository = repository;
//    }

    @PostMapping("/generate")
    public ResponseEntity<String> generateCode(@RequestBody Map<String, String> request) {
        String content = request.get("content");
        String shortCode = generateShortCode();
        
        DynamicCode code = new DynamicCode();
        code.setShortCode(shortCode);
        code.setContent(content);
        code.setLastUpdated(LocalDateTime.now());

        dynamicCodeMapper.insert(code);
        
        String qrCodeUrl = "https://192.168.2.4:8081/qr/" + shortCode;
        return ResponseEntity.ok(qrCodeUrl);
    }

    @GetMapping("/qr/{shortCode}")
    public void redirectFromQr(HttpServletResponse response,
                               @PathVariable String shortCode) throws IOException {
        DynamicCode code = dynamicCodeMapper.selectOne(new LambdaQueryWrapper<DynamicCode>()
                .eq(DynamicCode::getShortCode, shortCode)
        );
        
        response.sendRedirect(code.getContent());
    }

    @PutMapping("/update/{shortCode}")
    public ResponseEntity<?> updateContent(@PathVariable String shortCode,
                                         @RequestBody Map<String, String> request) {
        DynamicCode code = dynamicCodeMapper.selectOne(new LambdaQueryWrapper<DynamicCode>()
                .eq(DynamicCode::getShortCode, shortCode)
        );
        
        code.setContent(request.get("content"));
        code.setLastUpdated(LocalDateTime.now());
        dynamicCodeMapper.updateById(code);
        
        return ResponseEntity.ok().build();
    }

    private String generateShortCode() {
        // 实现一个生成6位随机字符串的逻辑
        return RandomStringUtils.randomAlphanumeric(6).toLowerCase();
    }
}